package SQL.scan;

import java.util.ArrayList;

import heap.ResultRow;
import heap.ResultSchema;
import Transaction.Transaction;

public class DistinctScan implements Scan {

	public DistinctScan(Scan s, String db, Transaction tx) throws Exception{
		this.s = s;
		schema = s.getSchema();
		ArrayList<SortKey> keys = new ArrayList<SortKey>();
		for(int i=0;i<schema.size();i++){
			keys.add(new SortKey(schema.get(i).name,true));
		}
		this.s = new SortScan(s,db,keys,tx);
		result = this.s.next();
	}
	
	@Override
	public void beforeFirst() throws Exception {
		s.beforeFirst();
	}

	@Override
	public void close() throws Exception {
		s.close();
	}

	@Override
	public ResultRow getCurrent() throws Exception {
		return result;
	}

	@Override
	public ResultSchema getSchema() throws Exception {
		return schema;
	}

	@Override
	public boolean hasField(String fldname) {
		return true;
	}

	@Override
	public ResultRow next() throws Exception {
		ResultRow next = s.next();
		while(next != null){
			if(isEqual(result, next)){
			next = s.next();	
			}
		}
		result = next;
		return result;
	}
	
	private boolean isEqual(ResultRow current, ResultRow next){
		boolean flag = false;
		if(current == null || next == null)
			return false;
		
		for(int i=0;i<schema.size();i++){
			if(!next.get(i).equals(current.get(i))){
				flag = true;
				break;
			}
		}
		return flag;
	}

	ResultSchema schema;
	ResultRow result;
	Scan s;
	
}
